<template>
  <Drawer
    v-model:visible="detailModal"
    title="查看SQL"
    width="80%"
    @close="handleDetailClose"
  >
    <!-- 顶部表格 -->
    <a-table
      :dataSource="[record]"
      :columns="columns"
      bordered
      size="small"
      pagination="false"
      style="margin-bottom: 16px"
    />
    <!-- 转换错误和建议 -->
    <div style="display: flex; gap: 16px; margin-bottom: 16px;">
      <div style="flex: 2;">
        <div style="font-weight: bold; margin-bottom: 4px;">转换错误</div>
        <a-alert
          v-for="(err, idx) in errors"
          :key="idx"
          :message="err"
          type="error"
          show-icon
          style="margin-bottom: 4px;"
        />
      </div>
      <div style="flex: 1;">
        <div style="font-weight: bold; margin-bottom: 4px;">建议</div>
        <a-alert
          message="为实现相同功能，更改应用代码和SQL语句。"
          type="info"
          show-icon
        />
      </div>
    </div>

    <!-- 按钮区 -->
    <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
      <!-- <a-button>修改历史</a-button> -->
      <a-button @click="triggerFileInput">导入</a-button>
      <input ref="fileInput" type="file" style="display:none" @change="handleFileChange" />
      <a-button @click="exportTddl">导出</a-button>
      <a-button @click="reset">重置</a-button>
      <a-button type="primary" @click="save">保存</a-button>
    </div>

    <!-- SQL代码区（Monaco高亮） -->
    <div style="display: flex; gap: 16px;">
      <div style="flex: 1; display: flex; flex-direction: column;">
        <div style="font-weight: bold; margin-bottom: 4px;">源端</div>
        <div ref="sourceEditorContainer" class="sql-editor"></div>
      </div>
      <div style="flex: 1; display: flex; flex-direction: column;">
        <div style="font-weight: bold; margin-bottom: 4px;">目标端</div>
        <div ref="targetEditorContainer" class="sql-editor"></div>
      </div>
    </div>
  </Drawer>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount ,defineExpose,nextTick} from 'vue';
import { Drawer, Table, Button, Alert,message } from 'ant-design-vue';
import * as monaco from 'monaco-editor';
import * as http from '@/api/flow/details';
import store from "@/store";
const record = ref({})
const detailModal = ref(false); // 控制抽屉显示
const handleDetailClose = () => {
  detailModal.value = false;
};
const open = (data) => {
  record.value = data
  detailModal.value = true;
  nextTick(() => {
    sourceEditorInstance = monaco.editor.create(sourceEditorContainer.value, {
      value: record.value.sddl,
      language: 'sql',
      readOnly: true,
      theme: 'vs-dark',
      fontSize: 14,
      minimap: { enabled: false },
      automaticLayout: true,
      lineNumbers: 'on',
      scrollBeyondLastLine: false,
    });
    targetEditorInstance = monaco.editor.create(targetEditorContainer.value, {
      value: record.value.tddl,
      language: 'sql',
      readOnly: false, // 允许编辑
      theme: 'vs-dark',
      fontSize: 14,
      minimap: { enabled: false },
      automaticLayout: true,
      lineNumbers: 'on',
      scrollBeyondLastLine: false,
    });
    // 监听内容变化
    targetEditorInstance.onDidChangeModelContent(() => {
      record.value.tddl = targetEditorInstance.getValue();
    });
  })
};
defineExpose({
  open
})

const columns = [
{ title: 'schema', dataIndex: 'schema', key: 'schema' },
  { title: '对象名', dataIndex: 'objName', key: 'objName' },
  { title: '对象类型', dataIndex: 'objType', key: 'objType' },
  { title: '迁移状态', dataIndex: 'migStatus', key: 'migStatus' },
  { title: '转换状态', dataIndex: 'switchStatus', key: 'switchStatus' },
  { title: '更新时间', dataIndex: 'updateTime', key: 'updateTime' },
];

// 错误信息
const errors = [];


// Monaco Editor相关
const sourceEditorContainer = ref(null);
const targetEditorContainer = ref(null);
let sourceEditorInstance = null;
let targetEditorInstance = null;

const fileInput = ref(null);

const triggerFileInput = () => {
  fileInput.value && fileInput.value.click();
}
const uploadFile = ref(null)
const handleFileChange = (e) => {
 
  const file = e.target.files[0];
  const reader = new FileReader();
  reader.onload = function(evt) {
    // 这里是异步回调
    const content = evt.target.result;
    console.log(content,'content')
    console.log('file:', file);
    uploadFile.value = file
    importTddl()
    // 2. 上传到服务器（异步）
    // uploadToServer(file, content);
  };
  reader.readAsText(file);
  // 清空input，防止同一文件多次上传无效
  e.target.value = '';
}

onMounted(() => {

});

onBeforeUnmount(() => {
  if (sourceEditorInstance) sourceEditorInstance.dispose();
  if (targetEditorInstance) targetEditorInstance.dispose();
});
// 导入
const importTddl = async () => {
  let formData = new FormData()
  formData.append('file',uploadFile.value)
  formData.append('id',record.value.id)
  formData.append('tokenID',sessionStorage.getItem('Admin-Token'))
  formData.append('flowId', 1751594386615)
  let params = {
    type:'formData',
    formData
  }
  // formData.append('flowId', store.state.taskInfo.selectMigrationFlow.flowId)
  let res = await http.importTddl(params)
  try{
    if(res.code === '000000'){
      message.success(res.msg)
      targetEditorInstance.setValue(res.msg)
      record.value.tddl = res.msg
    }
  }catch(error){
    console.log(error, "error");
    message.error(res.msg)
  }
}
// 导出
const exportTddl = async () => {
  let params = {
    flowId:1751594386615,
    // flowId: store.state.taskInfo.selectMigrationFlow.flowId,
    id:record.value.id
  }
  let res = await http.exportTddl(params)
  try{
    if(res.code === '999999'){
      message.error(res.msg)
      return
    }
    download(record.value.schema,res)
  }catch(error){
    console.log(error, "error");
    message.error(res.msg)
  }
}
const download = (filename,text) => {
		var pom = document.createElement("a");
		pom.setAttribute(
		  "href",
		  "data:text/plain;charset=utf-8," + encodeURIComponent(text)
		);
		pom.setAttribute("download", filename);
		if (document.createEvent) {
		  var event = document.createEvent("MouseEvents");
		  event.initEvent("click", true, true);
		  pom.dispatchEvent(event);
		} else {
		  pom.click();
		}
	}
  // 重置
  const reset = async () => {
    let params = {
      flowId:1751594386615,
      // flowId: store.state.taskInfo.selectMigrationFlow.flowId,
      id:record.value.id
    }
    let res = await http.reset(params)
    try{
      if(res.code === '000000'){
        message.success(res.msg)
      }
    }catch(error){
      console.log(error, "error");
    }
  }
// 保存
const save = async () => {
  let params = {
    flowId:1751594386615,
    // flowId: store.state.taskInfo.selectMigrationFlow.flowId,
    tddl:record.value.tddl,
    id:record.value.id
  }
  let res = await http.sqlsave(params)
  try{
    if(res.code === '000000'){
      message.success(res.msg)
    }
  }catch(error){
    console.log(error, "error");
  }
}
</script>

<style scoped>
:deep(.ant-table) {
  font-size: 13px;
}
.sql-editor {
  height: 260px;
  border: 1px solid #eee;
  margin-bottom: 16px;
  border-radius: 4px;
  overflow: hidden;
}
</style>